<template>
  <div>
    <!--1.视图-->
    <div class="deptDiv">
      <el-input
          prefix-icon="el-icon-search"
          placeholder="请输入部门名称"
          v-model="deptSearchName">
      </el-input>
      <el-tree
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="handleNodeSelectDeptByTreeId"
          ref="tree">
      </el-tree>
    </div>

    <div class="userDiv">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input v-model="formInline.userName" placeholder="请输入用户名称"></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="formInline.phonenumber" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="用户状态">
        <el-select v-model="formInline.status" placeholder="请输入用户状态">
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-col :span="11">
          <el-date-picker
              v-model="formInline.createTime"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期">
          </el-date-picker>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-date-picker
              v-model="formInline.updateTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="更新日期">
          </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-icon-search" @click="list">搜索</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" class="el-icon-plus" plain @click="openAdd">新增</el-button>
    <el-button type="success" @click="updateAll" class="el-icon-edit" plain>修改</el-button>
    <el-button type="info" @click="delAll" class="el-icon-delete" plain>删除</el-button>
    <el-button type="warning" class="el-icon-upload2" plain>导入</el-button>
    <el-button type="danger" @click="excelOut" class="el-icon-download" plain>导出</el-button>
    <template>
      <el-table
          ref="multipleTable"
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            fixed
            prop="userId"
            label="用户编号"
            sortable
            width="150">
        </el-table-column>
        <el-table-column
            prop="userName"
            label="用户名称"
            width="120">
        </el-table-column>
        <el-table-column
            prop="postName"
            label="岗位"
            width="120">
        </el-table-column>
        <el-table-column
            prop="deptName"
            label="部门"
            width="120">
        </el-table-column>
        <el-table-column
            prop="phonenumber"
            label="手机号码"
            width="300">
        </el-table-column>
        <el-table-column
            prop="pname"
            label="省"
            width="300">
        </el-table-column>
        <el-table-column
            prop="sname"
            label="市"
            width="300">
        </el-table-column>
        <el-table-column
            prop="xname"
            label="县"
            width="300">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="120">
          <template v-slot="s">
            <el-switch
                style="display: block"
                v-model="s.row.status"
                active-value="0"
                inactive-value="1"
                active-color="#01bbff"
                inactive-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            sortable
            width="160">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="250">
          <template slot-scope="scope">
            <el-button class="el-icon-edit" @click="openUpdate(scope.row)" type="text" size="small">修改</el-button>
            <el-button  class="el-icon-delete" @click="delAById(scope.row.userId)" type="text" size="small">删除</el-button>
            <el-button  class="el-icon-d-arrow-right" type="text" size="small">更多</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[3, 6, 9]"
          :page-size="size"
          layout="sizes, prev, pager, next"
          :total="total">
      </el-pagination>
    </template>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLabelWidth" prop="phonenumber">
          <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth" prop="password">
          <el-input show-password v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户性别" :label-width="formLabelWidth" prop="sex">
          <template>
            <el-radio v-model="form.sex" label="0">男</el-radio>
            <el-radio v-model="form.sex" label="1">女</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <template>
            <el-radio v-model="form.status" label="0">正常</el-radio>
            <el-radio v-model="form.status" label="1">停用</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="岗位" :label-width="formLabelWidth" prop="postsId">
          <el-select v-model="form.postsId" :multiple="true">
            <el-option
                v-for="p in posts"
                :key="p.postId"
                :label="p.postName"
                :value="p.postId">
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="角色" :label-width="formLabelWidth">-->
<!--          <el-checkbox-group v-model="form.rids">-->
<!--            <el-checkbox  v-for="r in roles"-->
<!--                          :key="r.roleId" :label="r.roleId">{{r.roleName}}</el-checkbox>-->
<!--          </el-checkbox-group>-->
<!--         </el-form-item>-->
        <el-form-item label="角色" :label-width="formLabelWidth" prop="rids">
          <el-select v-model="form.rids" :multiple="true">
            <el-option  v-for="r in roles"
                        :key="r.roleId"
                        :label="r.roleName"
                        :value="r.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" :label-width="formLabelWidth" prop="deptId">
          <el-select v-model="deptName" placeholder="请选择">
            <el-option :label="menuName" :value="menuId" style="height: 200px;">
              <el-tree
                       :data="data"
                       :props="defaultProps"
                       @node-click="handleNodeClick">
              </el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省市县" :label-width="formLabelWidth">
          <el-cascader
              v-model="selectedpsx"
              :options="options"
              :props="props"
              @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="saveAddOrUpdate==1" type="primary" @click="saveUser('form')">添 加</el-button>
        <el-button v-if="saveAddOrUpdate==2" type="primary" @click="saveUpdate('form')">修 改</el-button>
      </div>
    </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "UserView",
  watch: {
    deptSearchName(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      //2.属性定义
      title:"添加用户",
      deptSearchName:'',
      saveAddOrUpdate:'',
      menuName:'',
      menuId:'',
      deptName:'',
      tableData:[],
      mids:[],
      roles:[],
      value:[],
      posts:[],
      depts:[],
      selectedpsx:[],
      props:{
        value:"id",
        label:"name",
      },
      options:[],
      multipleSelection:[],
      total:0,
      current:1,
      size:3,
      formInline:{},
      form:{
        rids:[],
        postsId:[],
      },
      dialogFormVisible:false,
      formLabelWidth:'120px',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        userName: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        phonenumber: [
          {required: true, message: '请输入手机号码', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请输入用户性别', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请输入状态', trigger: 'blur'}
        ],
        postsId: [
          {required: true, message: '请输入岗位', trigger: 'blur'}
        ],
        rids: [
          {required: true, message: '请输入角色', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '请输入部门', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入备注', trigger: 'blur'}
        ],
      }
    }
  }, methods: {
    //3.方法
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleNodeSelectDeptByTreeId(data){
      this.formInline.deptId=data.id;
      this.list();
    },
    excelOut(){
      window.location.href="http://localhost:8000/carsystem/sysUser/excelOut";
    },
    resetForm() {
      this.formInline={};
      this.list();
    },
    updateAll(){
      this.title="修改用户";
      this.selectedpsx=[];
      let userId = this.multipleSelection.map(o=>o.userId);
      if(userId.length==0){
        this.$message.info("请选择一个用户");
      }else{
        this.form={rids:[],postsId:[]};
        this.saveAddOrUpdate=2;
        this.axios.post("http://localhost:8000/carsystem/sysUser/selectUserById?userId="+userId).then(res=>{
          this.form=res.data.data;
          this.dialogFormVisible=true;
          this.selectedpsx.push(this.form.pid+'');
          this.selectedpsx.push(this.form.sid+'');
          this.selectedpsx.push(this.form.xid+'');
          this.deptName=res.data.data.deptName;
          this.from.deptId=res.data.data.id;
        })
      }
      //岗位数据
      this.postsList();
      //角色数据
      this.rolesList();
      //回显角色数据
      this.rolesById(userId);
      //回显岗位数据
      this.postById(userId);
      //部门数据
      this.deptsList();
    },
    delAById(userId){
      // alert(userId);
      this.axios.post("http://localhost:8000/carsystem/sysUser/delAll?userId="+userId).then(res=>{
        if(res.data.code==200){
          this.$message.success(res.data.msg);
          this.list();
        }else{
          this.$message.error(res.data.msg);
        }
      })
    },
    delAll(){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let userId = this.multipleSelection.map(o=>o.userId);
        // alert(userId);
        this.axios.post("http://localhost:8000/carsystem/sysUser/delAll?userId="+userId).then(res=>{
          if(res.data.code==200){
            this.$message.success(res.data.msg);
            this.list();
          }else{
            this.$message.error(res.data.msg);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    saveUpdate(formName){
      // alert(JSON.stringify(this.form))
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("http://localhost:8000/carsystem/sysUser/updateUser",this.form).then(res=>{
            if(res.data.code==200){
              this.$message.success(res.data.msg);
              this.dialogFormVisible=false;
              this.list();
            }else{
              this.$message.error(res.data.msg);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    openUpdate(row){
      this.title="修改用户";
      this.form={rids:[],postsId:[]};
      this.saveAddOrUpdate=2;
      let userId = row.userId;
      this.axios.post("http://localhost:8000/carsystem/sysUser/selectUserById?userId="+userId).then(res=>{
        this.form=res.data.data;
        this.deptName=res.data.data.deptName;
        this.from.deptId=res.data.data.id;
      })
      this.dialogFormVisible=true;
      //岗位数据
      this.postsList();
      //角色数据
      this.rolesList();
      //回显角色数据
      this.rolesById(userId);
      //回显岗位数据
      this.postById(userId);
      //部门数据、






      this.deptsList();
      //还原
      this.selectedpsx=[];
      if(row.pid!=null){
        this.selectedpsx.push(row.pid+'');
        this.selectedpsx.push(row.sid+'');
        this.selectedpsx.push(row.xid+'');
      }
    },
    postById(userId){
      this.axios.post("http://localhost:8000/carsystem/sysUser/postById?userId="+userId).then(res=>{
        this.form.postsId=res.data.data;
      })
    },
    rolesById(userId){
      this.axios.post("http://localhost:8000/carsystem/sysUser/rolesById?userId="+userId).then(res=>{
          this.form.rids=res.data.data;
      })
    },
    handleNodeClick(data) {
      console.log(data);
      this.form.deptId= data.id;
      this.deptName= data.name;
      this.menuName=data.name;
      this.menuId=data.id;
    },
    saveUser(formName){
      // alert(JSON.stringify(this.form))
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("http://localhost:8000/carsystem/sysUser/saveUser",this.form).then(res=>{
            if(res.data.code==200){
              this.$message.success(res.data.msg);
              this.dialogFormVisible=false;
              this.list();
            }else{
              this.$message.error(res.data.msg);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    openAdd(){
      this.form={rids:[],postsId:[]};
      this.saveAddOrUpdate=1;
      this.dialogFormVisible=true;
      //岗位数据
      this.postsList();
      //角色数据
      this.rolesList();
      //部门数据
      this.deptsList();
    },
    deptsList(){
      this.axios.post("http://localhost:8000/carsystem/sysDept/deptsList").then(res=>{
        this.data=res.data.data;
        console.log(this.data);
      })
    },
    postsList(){
      this.axios.post("http://localhost:8000/carsystem/sysPost/postsList").then(res=>{
        this.posts=res.data.data;
      })
    },
    rolesList(){
      this.axios.post("http://localhost:8000/carsystem/sysRole/rolesList").then(res=>{
        this.roles=res.data.data;
      })
    },
    list(){
      this.axios.post("http://localhost:8000/carsystem/sysUser/list?current="+this.current+'&size='+this.size,this.formInline).then(res=>{
        this.tableData=res.data.data.list;
        this.total=res.data.data.total;
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size=val;
      this.list();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current=val;
      this.list();
    },
    handleChange(value) {
      console.log(value);
      this.selectedpsx=value;
      console.log(this.selectedpsx);
     if(value!=null&&value.length>0){
       this.form.xid = value[value.length-1];
       this.form.sid = value[value.length-2];
       this.form.pid = value[value.length-3];
     }
    },
    cityMenu(){
      this.axios.post("http://localhost:8000/carsystem/city/cityMenu").then(res=>{
        console.log(res.data.data);
        this.options=res.data.data;
      })
    },
  }, created() {
    //4.钩子函数
    this.list();
    this.cityMenu();
    this.deptsList();
  },

}
</script>

<style>

.deptDiv{
  display:inline-block;
  width: 20%;
  height: 100vh;
  float: left;
}
.userDiv{
  display:inline-block;
  width: 80%;
  height: 100vh;
  float: right;
}
</style>